import { ref, onMounted, onUnmounted, computed } from 'vue'

// Core Web Vitals 接口
interface WebVitalsMetrics {
  FCP?: number  // First Contentful Paint
  LCP?: number  // Largest Contentful Paint
  FID?: number  // First Input Delay
  CLS?: number  // Cumulative Layout Shift
  TTFB?: number // Time to First Byte
}

// 性能观察器
export function usePerformanceMonitor() {
  const metrics = ref<WebVitalsMetrics>({})
  const isSupported = ref(false)
  const observers = ref<PerformanceObserver[]>([])

  // 检查浏览器支持
  onMounted(() => {
    isSupported.value = 'PerformanceObserver' in window && 'PerformanceNavigationTiming' in window
    if (isSupported.value) {
      startMonitoring()
    }
  })

  // 开始监控
  const startMonitoring = () => {
    // FCP 监控
    observeMetric('paint', (entries) => {
      const fcpEntry = entries.find(entry => entry.name === 'first-contentful-paint')
      if (fcpEntry) {
        metrics.value.FCP = fcpEntry.startTime
      }
    })

    // LCP 监控
    observeMetric('largest-contentful-paint', (entries) => {
      const lcpEntry = entries[entries.length - 1]
      if (lcpEntry) {
        metrics.value.LCP = lcpEntry.startTime
      }
    })

    // FID 监控
    observeMetric('first-input', (entries) => {
      const fidEntry = entries[0]
      if (fidEntry) {
        metrics.value.FID = fidEntry.processingStart - fidEntry.startTime
      }
    })

    // CLS 监控
    observeMetric('layout-shift', (entries) => {
      let clsValue = 0
      entries.forEach(entry => {
        if (!entry.hadRecentInput) {
          clsValue += entry.value
        }
      })
      metrics.value.CLS = clsValue
    })

    // TTFB 监控
    const navigationEntry = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming
    if (navigationEntry) {
      metrics.value.TTFB = navigationEntry.responseStart - navigationEntry.fetchStart
    }
  }

  // 通用观察器创建函数
  const observeMetric = (type: string, callback: (entries: any[]) => void) => {
    try {
      const observer = new PerformanceObserver((list) => {
        callback(list.getEntries())
      })
      observer.observe({ type, buffered: true })
      observers.value.push(observer)
    } catch (error) {
      console.warn(`无法监控 ${type} 指标:`, error)
    }
  }

  // 获取性能评分
  const getPerformanceScore = computed(() => {
    const scores = {
      FCP: getFCPScore(metrics.value.FCP),
      LCP: getLCPScore(metrics.value.LCP),
      FID: getFIDScore(metrics.value.FID),
      CLS: getCLSScore(metrics.value.CLS)
    }
    
    const validScores = Object.values(scores).filter(score => score !== null)
    const averageScore = validScores.length > 0 
      ? validScores.reduce((sum, score) => sum + score!, 0) / validScores.length
      : 0
    
    return {
      overall: Math.round(averageScore),
      breakdown: scores
    }
  })

  // 评分函数
  const getFCPScore = (fcp?: number): number | null => {
    if (!fcp) return null
    if (fcp <= 1800) return 100
    if (fcp <= 3000) return Math.round(100 - ((fcp - 1800) / 1200) * 50)
    return 50
  }

  const getLCPScore = (lcp?: number): number | null => {
    if (!lcp) return null
    if (lcp <= 2500) return 100
    if (lcp <= 4000) return Math.round(100 - ((lcp - 2500) / 1500) * 50)
    return 50
  }

  const getFIDScore = (fid?: number): number | null => {
    if (!fid) return null
    if (fid <= 100) return 100
    if (fid <= 300) return Math.round(100 - ((fid - 100) / 200) * 50)
    return 50
  }

  const getCLSScore = (cls?: number): number | null => {
    if (!cls) return null
    if (cls <= 0.1) return 100
    if (cls <= 0.25) return Math.round(100 - ((cls - 0.1) / 0.15) * 50)
    return 50
  }

  // 清理监控
  onUnmounted(() => {
    observers.value.forEach(observer => observer.disconnect())
  })

  return {
    metrics: computed(() => metrics.value),
    performanceScore: getPerformanceScore,
    isSupported
  }
}

// 资源加载优化
export function useResourceOptimization() {
  const resourceMetrics = ref<PerformanceResourceTiming[]>([])
  
  // 获取资源加载性能
  const getResourceMetrics = () => {
    const resources = performance.getEntriesByType('resource') as PerformanceResourceTiming[]
    resourceMetrics.value = resources
    
    return {
      totalResources: resources.length,
      totalSize: resources.reduce((sum, resource) => sum + (resource.transferSize || 0), 0),
      slowestResources: resources
        .filter(resource => resource.duration > 1000)
        .sort((a, b) => b.duration - a.duration)
        .slice(0, 10),
      largestResources: resources
        .filter(resource => resource.transferSize > 0)
        .sort((a, b) => (b.transferSize || 0) - (a.transferSize || 0))
        .slice(0, 10)
    }
  }

  return {
    resourceMetrics: computed(() => resourceMetrics.value),
    getResourceMetrics
  }
}

// 内存使用监控
export function useMemoryMonitor() {
  const memoryInfo = ref<any>(null)
  const isSupported = ref(false)

  onMounted(() => {
    // @ts-ignore - Chrome specific API
    isSupported.value = 'memory' in performance
    if (isSupported.value) {
      updateMemoryInfo()
      // 每30秒更新一次内存信息
      const interval = setInterval(updateMemoryInfo, 30000)
      onUnmounted(() => clearInterval(interval))
    }
  })

  const updateMemoryInfo = () => {
    if (isSupported.value) {
      // @ts-ignore
      memoryInfo.value = performance.memory
    }
  }

  const getMemoryUsage = computed(() => {
    if (!memoryInfo.value) return null
    
    return {
      used: Math.round(memoryInfo.value.usedJSHeapSize / 1024 / 1024), // MB
      total: Math.round(memoryInfo.value.totalJSHeapSize / 1024 / 1024), // MB
      limit: Math.round(memoryInfo.value.jsHeapSizeLimit / 1024 / 1024), // MB
      usage: Math.round((memoryInfo.value.usedJSHeapSize / memoryInfo.value.totalJSHeapSize) * 100) // %
    }
  })

  return {
    memoryUsage: getMemoryUsage,
    isSupported
  }
}

// 网络状态监控
export function useNetworkMonitor() {
  const networkInfo = ref<any>(null)
  const isOnline = ref(navigator.onLine)

  onMounted(() => {
    // @ts-ignore - Network Information API
    if ('connection' in navigator) {
      // @ts-ignore
      networkInfo.value = navigator.connection
    }

    // 监听网络状态变化
    const handleOnline = () => { isOnline.value = true }
    const handleOffline = () => { isOnline.value = false }
    
    window.addEventListener('online', handleOnline)
    window.addEventListener('offline', handleOffline)

    onUnmounted(() => {
      window.removeEventListener('online', handleOnline)
      window.removeEventListener('offline', handleOffline)
    })
  })

  const networkStatus = computed(() => {
    if (!networkInfo.value) return null
    
    return {
      effectiveType: networkInfo.value.effectiveType, // '4g', '3g', '2g', 'slow-2g'
      downlink: networkInfo.value.downlink, // Mbps
      rtt: networkInfo.value.rtt, // ms
      saveData: networkInfo.value.saveData // boolean
    }
  })

  return {
    isOnline,
    networkStatus
  }
}

// 长任务监控
export function useLongTaskMonitor() {
  const longTasks = ref<PerformanceEntry[]>([])
  const observer = ref<PerformanceObserver | null>(null)

  onMounted(() => {
    if ('PerformanceObserver' in window && 'PerformanceLongTaskTiming' in window) {
      observer.value = new PerformanceObserver((list) => {
        const tasks = list.getEntries()
        longTasks.value.push(...tasks)
        
        // 只保留最近的100个长任务
        if (longTasks.value.length > 100) {
          longTasks.value = longTasks.value.slice(-100)
        }
      })
      observer.value.observe({ entryTypes: ['longtask'] })
    }
  })

  onUnmounted(() => {
    observer.value?.disconnect()
  })

  const longTasksMetrics = computed(() => {
    if (longTasks.value.length === 0) return null
    
    const totalDuration = longTasks.value.reduce((sum, task) => sum + task.duration, 0)
    const averageDuration = totalDuration / longTasks.value.length
    const maxDuration = Math.max(...longTasks.value.map(task => task.duration))
    
    return {
      count: longTasks.value.length,
      totalDuration: Math.round(totalDuration),
      averageDuration: Math.round(averageDuration),
      maxDuration: Math.round(maxDuration)
    }
  })

  return {
    longTasksMetrics
  }
}

// 综合性能监控composable
export function usePerformance() {
  const performanceMonitor = usePerformanceMonitor()
  const resourceOptimization = useResourceOptimization()
  const memoryMonitor = useMemoryMonitor()
  const networkMonitor = useNetworkMonitor()
  const longTaskMonitor = useLongTaskMonitor()

  // 生成性能报告
  const generatePerformanceReport = () => {
    return {
      timestamp: new Date().toISOString(),
      webVitals: performanceMonitor.metrics.value,
      performanceScore: performanceMonitor.performanceScore.value,
      resources: resourceOptimization.getResourceMetrics(),
      memory: memoryMonitor.memoryUsage.value,
      network: networkMonitor.networkStatus.value,
      longTasks: longTaskMonitor.longTasksMetrics.value
    }
  }

  // 性能优化建议
  const getOptimizationSuggestions = computed(() => {
    const suggestions: string[] = []
    const metrics = performanceMonitor.metrics.value
    const score = performanceMonitor.performanceScore.value

    if (metrics.FCP && metrics.FCP > 3000) {
      suggestions.push('首屏渲染时间过长，建议优化关键资源加载')
    }
    
    if (metrics.LCP && metrics.LCP > 4000) {
      suggestions.push('最大内容渲染时间过长，建议优化大型元素加载')
    }
    
    if (metrics.FID && metrics.FID > 300) {
      suggestions.push('首次输入延迟过长，建议减少主线程阻塞')
    }
    
    if (metrics.CLS && metrics.CLS > 0.25) {
      suggestions.push('累积布局偏移过大，建议稳定页面布局')
    }

    if (score.overall < 70) {
      suggestions.push('整体性能较差，建议进行全面性能优化')
    }

    return suggestions
  })

  return {
    ...performanceMonitor,
    ...resourceOptimization,
    ...memoryMonitor,
    ...networkMonitor,
    ...longTaskMonitor,
    generatePerformanceReport,
    optimizationSuggestions: getOptimizationSuggestions
  }
} 